package practise.alogrithm.gotoSiliconValley.array;

import java.util.Arrays;

/**
 * Created by Richard on 8/4/2014.
 */
public class MostClosestNumberFromArray {
    public int mostCloseNumber(int[] arrayA, int[] arrayB){
        if(arrayA==null || arrayB==null || arrayA.length!=arrayB.length){
            throw new IllegalArgumentException();
        }
        Arrays.sort(arrayA);
        int result=0;
        boolean[] used = new boolean[arrayA.length];
        for(int index=0; index<arrayB.length;index++){
            //find out the first value in A which is not less than element in B
            int indexA =0;
            for(; indexA< arrayA.length&&arrayA[indexA]<arrayB[index];indexA++){
                if(!used[indexA]){
                    break;
                }
            }
            if(indexA==arrayA.length-1&&arrayA[indexA]<arrayB[index]&&!used[indexA]){
                // don't have any number that can larger than number B;
                return -1;
            }
            else{
                used[indexA]=true;
                result=result*10+arrayA[indexA];
                if(arrayA[indexA]>arrayB[index]){
                    // current number is already larger than arrayB, we need get the least number from the rest number
                    for(int inner=0; inner<arrayA.length;inner++){
                        if(!used[inner]){
                            result=result*10+arrayA[inner];
                        }
                    }
                    return result;
                }
            }
        }
        return result;
    }

}
